import { Button } from '@nutui/nutui-react-taro';
import { View, Text } from '@tarojs/components';
import { IUser } from '@/types/user';
import Taro, { useDidShow } from '@tarojs/taro';
import { useDispatch } from 'react-redux';
import { setTabbarIndex } from '@/store/system-slice';
import request from '@/utils/request';
import { useState, useEffect } from 'react';
import { ICoupon } from '@/types/coupon';
import { IOrder } from '@/types/order';
import './row-display.less';

interface IProps {
  user: IUser;
}

export default function Index(props: IProps) {
  const { user } = props;
  const dispatch = useDispatch();
  const [orderCount, setOrderCount] = useState<number>(0);
  const [couponCount, setCouponCount] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  
  /**
   * 获取订单数量
   */
  const fetchOrderCount = async () => {
    if (!user?.id) return;
    
    try {
      const orders = await request.get<IOrder[]>('/order/list', {
        id: user.id,
      });
      setOrderCount(orders?.length || 0);
    } catch (error) {
      console.error('获取订单数量失败:', error);
    }
  };

  /**
   * 获取优惠券数量
   */
  const fetchCouponCount = async () => {
    if (!user?.id) return;
    
    try {
      const coupons = await request.get<ICoupon[]>('/coupon', {
        userId: user.id,
      });
      setCouponCount(coupons?.length || 0);
    } catch (error) {
      console.error('获取优惠券数量失败:', error);
    }
  };

  /**
   * 刷新所有数据
   */
  const refreshData = async () => {
    if (!user?.id) return;
    
    setLoading(true);
    try {
      await Promise.all([
        fetchOrderCount(),
        fetchCouponCount()
      ]);
    } catch (error) {
      console.error('刷新数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载和用户信息更新时获取数据
  useEffect(() => {
    refreshData();
  }, [user?.id]);

  // 每次页面显示时刷新数据
  useDidShow(() => {
    refreshData();
  });
  
  const goRechargePage = () => {
    if (!user) {
      Taro.navigateTo({ url: '/pages/login/index' });
      return;
    }
    // 切换到底部导航栏的订单页面（索引为1）
    dispatch(setTabbarIndex(1));
  };

  const goWithdrawalPage = () => {
    if (!user) {
      Taro.navigateTo({ url: '/pages/login/index' });
      return;
    }
    // 切换到底部导航栏的首页（索引为0）
    dispatch(setTabbarIndex(0));
  };

  return (
    <View className="mine-row-display">
      <View className="display-item display-item-left">
        <View className="title">我的订单</View>
        <View className="button-box">
          <View>
            <Text className="text-number">
              {user ? (loading ? '--' : orderCount) : '--'}&nbsp;个
            </Text>
          </View>
          <Button size="small" onClick={goRechargePage}>
            去查看
          </Button>
        </View>
      </View>
      <View className="display-item display-item-right">
        <View className="title">我的优惠券</View>
        <View className="button-box">
          <View>
            <Text className="text-number">
              {user ? (loading ? '--' : couponCount) : '--'}&nbsp;张
            </Text>
          </View>
          <Button size="small" onClick={goWithdrawalPage}>
            去下单
          </Button>
        </View>
      </View>
    </View>
  );
}
